<?php
/**
 * Basic class to decode minimal bbcode
 * (unsafe, far from full proof... use with care)
 *
 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
 * @author     Stephane Chamberland <dokuwiki@meteokid.ca>
 */
 */
class ACC_bbcode {

    /**
     *
     */
    function decode($mystring){
        $mystring .= "\n";
        //$mystring = str_replace('<br />',"\n<br />\n", $mystring);
        $mystring = str_replace(array('<br />','<br>','<br/>'),array("\n","\n","\n"), $mystring);
        //transform [img]SOMEURL[/img] and [url=SOMEURL]SOMETEXT[/url] and [url]SOMEURL[/url]
        //transform http://*.(jpg|gif|png) to image
        //Transform http:// and https:// to real links
        $search_replace = array(
            '/\[b\](.*?)\[\/b\]/is' => '<strong>$1</strong>',
            '/\[i\](.*?)\[\/i\]/is'    => '<em>$1</em>',
            '/\[u\](.*?)\[\/u\]/is' =>  '<u>$1</u>',
            '/\[quote\](.*?)\[\/quote\]/is' => '<blockquote><p>$1</p></blockquote>',
            '/\[img\](.*?)\[\/img\]/is' =>  '<img src="$1" style="float:right;"/>',
            '/\[url\](.*?)\[\/url\]/is' =>  '<a href="$1">$1</a>',
            '/\[url\=(.*?)\](.*?)\[\/url\]/is' => '<a href="$1">$2</a>',
            '/\b(http[s]?:)([^\s\t\n]+)(\.jpg|\.gif|\.png)([\s\t\n])/i' => '<img src="${1}${2}${3}" />$4',
            '/([^">])\b(http[s]?:)([^\s\t\n]+)([\s\t\n])/i' => '${1}<a href="${2}${3}">${2}${3}</a>$4',
            //Some cleanup
            '/(<br \/>)+[\n\s]+(<br \/>)+/' => '$1$2',
            '/(<br \/>)(<br \/>)+/' => '$1$1',
            '/(<br \/>)+[\n\s]*<img/' => '<br /><img'
        );
        $search = array_keys($search_replace);
        $replace = array_values($search_replace);
        $mystring = preg_replace($search, $replace, $mystring);

        //remove remaining BBcode
        $search = array('[b]','[i]','[u]','[quote]','[img]','[url]');
        $replace = array(' ',' ',' ',' ',' ',' ');
        $mystring = str_replace($search, $replace, $mystring);

        //return str_replace("\n",' ',$mystring);
        return str_replace("\n",'<br />',trim($mystring));
    }

}
